<template>
  <page-meta :root-font-size="$rootFontSize"></page-meta>
  <view>
    <!--banner-->
    <view class="bannerImg mb-3" @click="goTo('guide')">
      <u--image :src="bannerImg" width="750rpx" height="1000rpx"></u--image>
    </view>
    <view class="mx-2.5 mb-3">
      <u-checkbox-group
        v-model="isApply"
        class="mt-4"
        iconSize="28rpx"
        @change="toBuyChange"
      >
        <u-checkbox
          size="32rpx"
          name="apply"
          activeColor="#FF3D62"
          shape="circle"
        ></u-checkbox>
        <view class="text-xs" @click="toBuyChange"> 仅展示我可申请的商品 </view>
      </u-checkbox-group>
    </view>
    <!--头部-->
    <view
      class="flex flex-wrap justify-between mx-2.5"
      v-if="infiniteList.length > 0"
    >
      <!--商品列表-->
      <view
        class="bg-white rounded-lg mb-3"
        style="width: 345rpx"
        v-for="(item, index) in infiniteList"
        :key="item.id"
        @click="goodDetail(item)"
      >
        <view class="py-2.5 mx-2.5 relative">
          <view
            class="absolute left-0 top-2.5"
            style="z-index: 1"
            v-if="item.saleStatus == 2"
          >
            <u--image
              src="/static/images/watermarkDone.png"
              width="300rpx"
              height="300rpx"
            ></u--image>
          </view>
          <u--image
            :src="item.productImg"
            width="300rpx"
            height="300rpx"
          ></u--image>
          <view class="text-sm leading-6 mt-2 u-line-1">{{
            item.activityName
          }}</view>
          <view class="text-base text-primary leading-6"
            ><text class="text-xs">到手价</text>￥
            {{ item.deliveryPrice }}</view
          >
        </view>
      </view>
    </view>
    <view class="text-center text-sm" v-else>- 暂无活动产品 -</view>
    <!--温馨提示-->
    <u-popup
      :show="user.hasPasswd == 0 && isDownload"
      mode="center"
      :round="30"
      @close="isDownload = false"
    >
      <view class="w-72 py-5">
        <view class="mx-6 relative">
          <view class="absolute right-0 top-1.5" @click="isDownload = false"
            ><u-icon name="close" color="#aaaaaa" size="28"></u-icon
          ></view>
          <view class="text-lg font-medium text-center">恭喜您注册成功</view>
          <view class="text-sm leading-6 mt-3"
            >当前为网页版，体验流畅度还不完整。为了方便您下次登录以及享受更多权益，现邀请您下载使用最新APP版本。</view
          >
          <view
            class="bg-primary rounded-full text-white flex justify-center py-2.5 mt-5"
            @click="toDownload(user.apkUrl)"
            ><u-icon name="/static/icons/icon-android.png" size="34"></u-icon
            >Android版下载</view
          >
          <view
            class="bg-primary rounded-full text-white flex justify-center py-2.5 mt-3"
            @click="toCopy(user.promotionLink)"
            ><u-icon name="/static/icons/icon-iPhone.png" size="34"></u-icon
            >iPhone网页版</view
          >
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapState } from 'vuex';
import { getBannerList, getProductList } from '../../services/common';
import { versionUpdate } from '../../services/user';
import infinite from '@/mixins/infinite';

export default {
  mixins: [infinite],
  data() {
    return {
      isDownload: true,
      isShow: false,
      currentIndex: 0,
      bannerImg: '',
      infiniteList: [],
      isEarnPrice: 0,
      isApply: [],
      isAllowBuy: 0,
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.user,
    }),
  },
  async onPullDownRefresh() {
    uni.stopPullDownRefresh();
  },
  async created() {
    this.getBanner();
    this.getInfiniteList();
    this.$store.dispatch('getUser');
  },
  methods: {
    //安卓版下载
    toDownload(link) {
      let dload = document.createElement('a');
      dload.download = ''; //
      dload.href = link;
      document.body.appendChild(dload);
      dload.click();
      dload.remove(); // 下载之后把创建的元素删除
    },
    //复制h5链接
    toCopy(content) {
      uni.setClipboardData({
        data: content,
        success: function () {
          uni.showToast({
            title: '链接复制成功',
            icon: 'none',
          });
        },
      });
    },
    //仅展示我可申请的商品
    toBuyChange() {
      this.isApply = this.isApply.length ? [] : ['apply'];
      this.isAllowBuy = this.isApply.length;
      this.getInfiniteList(true);
    },
    //版本号检查&检查更新
    async checkUpdate(version) {
      const { code, data } = await versionUpdate({ version });
      if (code != 200) return;
      if (data.update) {
        this._download(data.url);
      }
    },
    //下载方法
    _download(url) {
      const dtask = plus.downloader.createDownload(url, {}, (d, status) => {
        //console.log(d, status);
        uni.showToast({
          title: '下载完成',
          icon: 'none',
        });
        if (status == 200) {
          plus.runtime.install(
            plus.io.convertLocalFileSystemURL(d.filename),
            {},
            () => {
              uni.showToast({
                title: '下载成功',
                icon: 'none',
              });
            },
            () => {
              uni.showToast({
                title: '安装失败-01',
                icon: 'none',
              });
            }
          );
        } else {
          uni.showToast({
            title: '更新失败-02',
            icon: 'none',
          });
        }
      });
      try {
        const loading = plus.nativeUI.showWaiting('正在下载', {
          back: 'none',
        });
        dtask.start();
        dtask.addEventListener('statechanged', (task, status) => {
          switch (task.state) {
            case 3:
              {
                const { downloadedSize, totalSize } = task;
                const progress = parseInt((downloadedSize / totalSize) * 100);
                loading.setTitle(`正在下载${progress}%`);
              }
              break;
            case 4:
              plus.nativeUI.closeWaiting();
              break;
          }
        });
      } catch {
        plus.nativeUI.closeWaiting();
        uni.showToast({
          title: '更新失败-03',
          icon: 'none',
        });
      }
    },
    //路由跳转
    goTo(url) {
      this.$Router.push({
        name: url,
      });
    },
    //首页banner
    async getBanner() {
      const { code, data } = await getBannerList();
      if (code != 200) return;
      //检查版本升级及下载安装apk自动升级
      // #ifdef APP-PLUS
      this.checkUpdate(plus.runtime.version);
      // #endif
      this.bannerImg = data[0].image;
    },
    //商品详情
    goodDetail(item) {
      const token = uni.getStorageSync(
        'tokenBuy' + process.env.VUE_APP_PLATFORMID
      );
      if (!token) {
        uni.reLaunch({
          url: '/login',
        });
      }
      this.$Router.push({
        name: 'good-detail',
        params: {
          id: item.id,
        },
      });
    },
    //产品列表
    async getInfiniteData(pageIndex, pageSize, diyType = 1) {
      let params = {
        pageNum: pageIndex,
        pageSize: pageSize,
        isAllowBuy: this.isAllowBuy,
      };
      const { code, data } = await getProductList(params);
      if (code != 200) return;
      return data.records;
    },
  },
};
</script>

<style>
page {
  background: #f1e0e7;
}
.bannerImg image {
  width: 750rpx;
  height: 1000rpx;
}
</style>
